package com.lujianfei.powersearch.base

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import com.lujianfei.powersearch.utils.StatusBarUtils
import com.lujianfei.powersearch.utils.ResUtils
import com.lujianfei.powersearch.R
import androidx.annotation.LayoutRes
import androidx.appcompat.widget.Toolbar
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider

abstract class BaseActivity<DB: ViewDataBinding?> : AppCompatActivity() {

    private var toolBar: Toolbar? = null
    protected var binding: DB?= null

    abstract fun resourceId():Int
    abstract fun initView()
    abstract fun initData()
    abstract fun initEvent()
    inline fun <reified VM: ViewModel> buildViewModel() = ViewModelProvider(this)[VM::class.java]

    open fun useStatusBarUtils():Boolean {
        return true
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        if (useStatusBarUtils()) {
            StatusBarUtils.with(this).setColor(ResUtils.getColor(R.color.colorPrimary)).init()
        }
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView<DB>(this, resourceId())
        initView()
        initEvent()
        initData()
    }

    override fun setContentView(@LayoutRes layoutResID: Int) {
        super.setContentView(layoutResID)
        toolBar = findViewById(titleBarResId)
        if (null == toolBar) {
            return
        }
        setSupportActionBar(toolBar)
        supportActionBar?.setDisplayHomeAsUpEnabled(showBackButton())
        supportActionBar?.setHomeButtonEnabled(showBackButton())
    }

    protected open fun showBackButton(): Boolean {
        return true
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        if (0 == menuResId) {
            return super.onCreateOptionsMenu(menu)
        }
        menuInflater.inflate(menuResId, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                finish()
            }
            else -> handleRightButton(item.itemId)
        }
        return super.onOptionsItemSelected(item)
    }

    protected open fun handleRightButton(itemId: Int) {}
    protected open val menuResId: Int
        get() = 0
    protected open val titleBarResId: Int
        get() = 0

    protected fun setTitleMiddleText(middleText: String?) {
        setTitleMiddleText(middleText, true)
    }

    protected fun setTitleMiddleText(middleText: String?, showMiddle: Boolean) {
        if (null != supportActionBar) {
            supportActionBar!!.title = middleText
        }
    }
}